import { http } from '../../request/index'
Page({
  data: {
    goodsObj:{},
    isCollect:false
  },
  //全局商品对象
  GoodsInfo:{},

  onLoad: function (options) {
    // console.log(options)
    const {goods_id} = options;
    this.getGoodsDetail(goods_id)
  },

  async getGoodsDetail(goods_id) {
    const goodsObj = await http({url:'/goods/detail', data: {goods_id}});
    //3.全局对象赋值
    this.GoodsInfo = goodsObj;
    //4.获取缓存中的商品收藏 回显;
    let collect = wx.getStorageSync('collect') || [];
    //5.判断当前商品是否被收藏;
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id)
    this.setData({
      //1.返回数据量过大 只留下用的到的
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        // 2.iphone部分手机 不识别 webp图片格式 前端进行处理
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.pics
      },
      isCollect
    });

    

  },

  //图片预览
  previewImage(e) {
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    const {current} = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },
  //加购车
  add_cart() {
    //1.获取缓存的购物车 数组第一次没有存肯定是[]
    const cart = wx.getStorageSync('cart') || [];
    //2.判断 商品对象是否存在数组中
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if(index === -1) {
      //不存在第一次添加 创建一个num记录
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo)
    }else {
      cart[index].num++;
    }
    //3.把购物车重新添加到缓存中
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加购成功',
      icon:'success',
      mask:true
    })
  },
  //收藏
  handleCollect() {
    let isCollect = false;
    let collect = wx.getStorageSync('collect') || [];
    let index = collect.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    if(index !== -1) {
      collect.splice(index, 1);
      isCollect = false;
      wx.showToast({
        title: '取消收藏',
        icon:'success',
        mask:true
      });
    }else {
      collect.push(this.GoodsInfo);
      isCollect = true;
      wx.showToast({
        title: '收藏成功',
        icon:'success',
        mask:true
      });
    }
    wx.setStorageSync('collect', collect)
    this.setData({
      isCollect
    })
  }
})